package com.grad.webstudy.aspect;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.grad.webstudy.model.es.ESLog;
import com.grad.webstudy.service.ElasticSearchService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.Objects;

/**
 * @Description: 日志记录切面
 * @Author: zjf
 * @Date: 2020/3/30 15:54.
 */

@Aspect
@Component
public class LogAspect {


    @Autowired
    private ElasticSearchService elasticSearchService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    ThreadLocal<Long> startTime = new ThreadLocal<Long>();

    Gson gson = new GsonBuilder()
            .setPrettyPrinting()
            .serializeSpecialFloatingPointValues() // 这是关键
            .create();

    private ESLog log = new ESLog();

    /**
     * 定义一个切入点.
     * 解释下：
     * <p>
     * ~ 第一个 * 代表任意修饰符及任意返回值.
     * ~ 第二个 * 任意包名
     * ~ 第三个 * 代表任意方法.
     * <p>
     * ~ 第四个 * 定义在web包或者子包
     * ~ 第五个 * 任意方法
     * ~ .. 匹配任意数量的参数.
     * execution(* xiao.ze.demo.service.impl.*.*(..))
     *
     * @Pointcut("execution(* com.grad.webstudy.service.impl.*.*(..))||" +
     * "execution(* com.grad.webstudy.controller.*.*(..))")
     */

    @Pointcut("execution(* com.grad.webstudy.controller.*.*(..)) &&" +
            "!execution(* com.grad.webstudy.controller.ElasticSearchController.queryLog(..)) &&" +
            "!execution(* com.grad.webstudy.controller.WebSocketServer.*(..)) ")
    public void webLog() {
    }


    @Pointcut("execution(* com.grad.webstudy.controller.ElasticSearchController.queryLog(..))")
    public void ESservice() {

    }


    @Before("ESservice()")
    public void serviceBefore(JoinPoint joinPoint) {
        startTime.set(System.currentTimeMillis());

        // 接收到请求，记录请求内容
        logger.info("ESserviceAspect.doBefore()");
        logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        logger.info("参数 : " + Arrays.toString(joinPoint.getArgs()));
    }


    @AfterReturning(returning = "result", pointcut = "ESservice()")
    public void serviceAfterReturning(JoinPoint joinPoint, Object result) {
        logger.info("ESserviceAspect.AfterReturn()");
        logger.info("耗时（毫秒） : " + (System.currentTimeMillis() - startTime.get()));
        logger.info("结果 : " + gson.toJson(result));
    }

    @AfterThrowing(pointcut = "ESservice()", throwing = "e")
    public void serviceException(JoinPoint joinPoint, Throwable e) {
        logger.info("serviceAspect.AfterThrowing()");
        logger.info("耗时（毫秒） : " + (System.currentTimeMillis() - startTime.get()));
        logger.error("异常信息 :\r\n" + stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace()));
    }


    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
        logger.info("测试热部署");
        startTime.set(System.currentTimeMillis());

        // 接收到请求，记录请求内容
        logger.info("WebLogAspect.doBefore()");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();


        // 记录下请求内容
        logger.info("URL : " + request.getRequestURL().toString());
        log.setRequestUrl(request.getRequestURL().toString());
        logger.info("请求方法 : " + request.getMethod());
        log.setTime(new Date());
        log.setType(request.getMethod());
        logger.info("IP : " + request.getRemoteAddr());
        log.setIp(request.getRemoteAddr());
        logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        logger.info("参数 : " + Arrays.toString(joinPoint.getArgs()));
        String params = "";
        //获取所有参数方法：
        Enumeration<String> enu = request.getParameterNames();
        while (enu.hasMoreElements()) {
            String paraName = (String) enu.nextElement();
            params += (paraName + ": " + request.getParameter(paraName)) + ", ";
        }
        logger.info("参数 : " + params);
        log.setParams(params);
    }

    @AfterReturning(returning = "result", pointcut = "webLog()")
    public void doAfterReturning(JoinPoint joinPoint, Object result) {

        // 处理完请求，返回内容
        logger.info("WebLogAspect.doAfterReturning()");
        logger.info("耗时（毫秒） : " + (System.currentTimeMillis() - startTime.get()));
        logger.info("结果 : " + gson.toJson(result));

        log.setResult(Objects.isNull(result) ? "" : result.toString());
        log.setStatus("成功");
        elasticSearchService.saveToES(log);
    }

    @AfterThrowing(pointcut = "webLog()", throwing = "e")
    public void doException(JoinPoint joinPoint, Throwable e) {
        logger.error("异常信息 :\r\n" + stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace()));
        logger.info("耗时（毫秒） : " + (System.currentTimeMillis() - startTime.get()));
        log.setStatus("失败");
        log.setResult(stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace()));
        elasticSearchService.saveToES(log);
    }

    /**
     * 转换异常信息为字符串
     *
     * @param exceptionName    异常名称
     * @param exceptionMessage 异常信息
     * @param elements         堆栈信息
     */
    public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
        StringBuffer strbuff = new StringBuffer();
        for (StackTraceElement stet : elements) {
            strbuff.append(stet + "\n");
        }
        String message = exceptionName + ":" + exceptionMessage + "\n" + strbuff.toString();
        return message;
    }
}
